import React, { useState, useEffect } from 'react';
import { Modal, Table, Tag, Typography, DatePicker, Select, Space, Button, Form, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

const { Text } = Typography;
const { RangePicker } = DatePicker;

interface ChatLog {
  id: number;
  status: number;
  username: string;
  realName: string;
  agentName: string;
  request_time: string;
  request_content: string;
  response_content: string | null;
  error_message: string | null;
  user_id: number;
  agent_id: number;
  create_time: string;
  update_time: string;
}

interface ChatLogModalProps {
  visible: boolean;
  onClose: () => void;
  initialStartTime?: string;
  initialEndTime?: string;
  initialStatus?: number;
}

const ChatLogModal: React.FC<ChatLogModalProps> = ({
  visible,
  onClose,
  initialStartTime,
  initialEndTime,
  initialStatus
}) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<ChatLog[]>([]);
  const [form] = Form.useForm();
  const [status, setStatus] = useState<number | undefined>(initialStatus);

  // 添加状态变化的监听
  useEffect(() => {
    if (visible) {
      fetchData();
    }
  }, [status]);

  const fetchData = async () => {
    try {
      const values = await form.validateFields();
      const { dateRange } = values;
      
      setLoading(true);
      const token = localStorage.getItem('token');
      
      // 构建查询参数
      const params = new URLSearchParams();
      if (dateRange && dateRange[0] && dateRange[1]) {
        params.append('startTime', dateRange[0].format('YYYY-MM-DD HH:mm:ss'));
        params.append('endTime', dateRange[1].format('YYYY-MM-DD HH:mm:ss'));
      } else if (initialStartTime && initialEndTime) {
        // 如果没有表单值但有初始值，使用初始值
        params.append('startTime', initialStartTime);
        params.append('endTime', initialEndTime);
      }
      // 只有当状态值不是undefined时才添加到查询参数中
      if (status !== undefined && status !== null) {
        params.append('status', status.toString());
      }
      
      const response = await fetch(
        `/engine/starhub/monitor/chat-logs${params.toString() ? `?${params.toString()}` : ''}`,
        {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        }
      );
      if (!response.ok) {
        throw new Error('获取数据失败');
      }
      const result = await response.json();
      if (result.status && result.data) {
        setData(result.data);
      } else {
        setData([]);
        message.error(result.msg || '获取数据失败');
      }
    } catch (error) {
      console.error('获取聊天日志失败:', error);
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 修改状态选择器的处理函数
  const handleStatusChange = (value: number | undefined) => {
    setStatus(value);
    // 状态改变时立即触发查询
    setTimeout(() => {
      fetchData();
    }, 0);
  };

  const columns = [
    {
      title: '请求时间',
      dataIndex: 'request_time',
      key: 'request_time',
      width: 180,
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '用户信息',
      key: 'userInfo',
      width: 150,
      render: (_: any, record: ChatLog) => (
        <div>
          <div>{record.username}</div>
          <Text type="secondary">{record.realName}</Text>
        </div>
      )
    },
    {
      title: '智能体',
      dataIndex: 'agentName',
      key: 'agentName',
      width: 120
    },
    {
      title: '请求内容',
      dataIndex: 'request_content',
      key: 'request_content',
      ellipsis: true
    },
    {
      title: '响应内容',
      dataIndex: 'response_content',
      key: 'response_content',
      ellipsis: true
    },
    {
      title: '错误信息',
      dataIndex: 'error_message',
      key: 'error_message',
      ellipsis: true,
      render: (text: string | null) => text ? <Text type="danger">{text}</Text> : '-'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: number) => {
        const statusMap = {
          0: { color: '#ff4d4f', text: '失败' },
          1: { color: '#52c41a', text: '成功' },
          2: { color: '#faad14', text: '告警' }
        };
        const { color, text } = statusMap[status as keyof typeof statusMap];
        return <Tag color={color}>{text}</Tag>;
      }
    }
  ];

  // 初始化表单值
  useEffect(() => {
    if (visible) {
      if (initialStartTime && initialEndTime) {
        form.setFieldsValue({
          dateRange: [dayjs(initialStartTime), dayjs(initialEndTime)]
        });
      } else {
        form.setFieldsValue({
          dateRange: undefined
        });
      }
      // 设置状态值并立即触发查询
      setStatus(initialStatus);
      setTimeout(() => {
        fetchData();
      }, 0);
    }
  }, [visible, initialStartTime, initialEndTime, initialStatus]);

  return (
    <Modal
      title="智能体调用日志记录详情"
      open={visible}
      onCancel={onClose}
      width={1200}
      footer={null}
    >
      <Form form={form} layout="inline" style={{ marginBottom: 16 }}>
        <Form.Item
          name="dateRange"
        >
          <RangePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            placeholder={['开始时间', '结束时间']}
            style={{ width: 400 }}
          />
        </Form.Item>
        <Form.Item>
          <Select
            style={{ width: 120 }}
            placeholder="状态"
            allowClear
            value={status}
            onChange={handleStatusChange}
            options={[
              { value: -1, label: '全部' },
              { value: 0, label: '失败' },
              { value: 1, label: '成功' },
              { value: 2, label: '告警' }
            ]}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" icon={<SearchOutlined />} onClick={fetchData}>
            查询
          </Button>
        </Form.Item>
      </Form>
      <Table
        columns={columns}
        dataSource={data}
        loading={loading}
        rowKey="id"
        scroll={{ y: 500 }}
        pagination={{
          total: data.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true
        }}
      />
    </Modal>
  );
};

export default ChatLogModal; 